import { defineStore } from 'pinia'
import { getOpportunityList, getOpportunityDetail, createOpportunity, updateOpportunity, deleteOpportunity } from '@/api/opportunity'
import { ElMessage } from 'element-plus'

export const useOpportunityStore = defineStore('opportunity', {
  state: () => ({
    // 机会列表
    opportunityList: [],
    // 当前查看的机会详情
    currentOpportunity: null,
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filters: {
      type: '',
      status: '',
      keyword: ''
    },
    // 最后更新时间
    lastFetchTime: 0,
    // 加载状态
    loading: false
  }),

  getters: {
    // 获取已筛选的机会列表
    filteredOpportunities: (state) => {
      let filtered = [...state.opportunityList]
      
      if (state.filters.type) {
        filtered = filtered.filter(item => item.type === state.filters.type)
      }
      
      if (state.filters.status) {
        filtered = filtered.filter(item => item.status === state.filters.status)
      }
      
      if (state.filters.keyword) {
        const keyword = state.filters.keyword.toLowerCase()
        filtered = filtered.filter(item => 
          (item.title && item.title.toLowerCase().includes(keyword)) ||
          (item.description && item.description.toLowerCase().includes(keyword))
        )
      }
      
      return filtered
    },
    
    // 检查是否需要刷新数据 (5分钟刷新一次)
    shouldRefreshData: (state) => {
      const now = Date.now()
      return (now - state.lastFetchTime) > 5 * 60 * 1000
    }
  },

  actions: {
    // 获取机会列表，添加智能刷新策略
    async fetchOpportunityList(params = {}, forceRefresh = false) {
      // 如果数据已存在且不需要强制刷新，直接返回缓存数据
      if (this.opportunityList.length > 0 && !forceRefresh && !this.shouldRefreshData) {
        return { list: this.opportunityList, total: this.pagination.total }
      }
      
      try {
        this.loading = true
        const res = await getOpportunityList({
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...this.filters,
          ...params
        })
        
        if (res.code === 200 && res.data) {
          this.opportunityList = res.data.list || []
          this.pagination = {
            page: params.page || this.pagination.page,
            pageSize: params.pageSize || this.pagination.pageSize,
            total: res.data.total || 0
          }
          this.lastFetchTime = Date.now()
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取机会列表失败:', error)
        ElMessage.error('获取机会列表失败')
        return null
      } finally {
        this.loading = false
      }
    },

    // 获取机会详情
    async fetchOpportunityDetail(id) {
      try {
        this.loading = true
        const res = await getOpportunityDetail(id)
        
        if (res.code === 200 && res.data) {
          this.currentOpportunity = res.data
          return res.data
        }
        return null
      } catch (error) {
        console.error('获取机会详情失败:', error)
        ElMessage.error('获取机会详情失败')
        return null
      } finally {
        this.loading = false
      }
    },

    // 创建机会
    async createOpportunity(opportunityData) {
      try {
        this.loading = true
        const res = await createOpportunity(opportunityData)
        
        if (res.code === 200 && res.data) {
          // 更新列表
          this.opportunityList.unshift(res.data)
          ElMessage.success('创建机会成功')
          return res.data
        }
        return null
      } catch (error) {
        console.error('创建机会失败:', error)
        ElMessage.error('创建机会失败')
        return null
      } finally {
        this.loading = false
      }
    },

    // 更新机会
    async updateOpportunity(id, opportunityData) {
      try {
        this.loading = true
        const res = await updateOpportunity(id, opportunityData)
        
        if (res.code === 200 && res.data) {
          // 更新列表中的数据
          const index = this.opportunityList.findIndex(item => item.id === id)
          if (index !== -1) {
            this.opportunityList[index] = res.data
          }
          ElMessage.success('更新机会成功')
          return res.data
        }
        return null
      } catch (error) {
        console.error('更新机会失败:', error)
        ElMessage.error('更新机会失败')
        return null
      } finally {
        this.loading = false
      }
    },

    // 删除机会
    async deleteOpportunity(id) {
      try {
        this.loading = true
        const res = await deleteOpportunity(id)
        
        if (res.code === 200) {
          // 从列表中移除
          this.opportunityList = this.opportunityList.filter(item => item.id !== id)
          ElMessage.success('删除机会成功')
          return true
        }
        return false
      } catch (error) {
        console.error('删除机会失败:', error)
        ElMessage.error('删除机会失败')
        return false
      } finally {
        this.loading = false
      }
    },

    // 更新筛选条件，优化为使用本地筛选
    updateFilters(filters) {
      this.filters = { ...this.filters, ...filters }
      
      // 如果已有数据，先在前端进行筛选
      if (this.opportunityList.length > 0 && !this.shouldRefreshData) {
        // 不立即调用后端API，使用前端过滤
        return
      }
      
      // 数据过期或没有数据时才请求API
      this.fetchOpportunityList({ page: 1 })
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        type: '',
        status: '',
        keyword: ''
      }
      // 使用强制刷新获取最新数据
      this.fetchOpportunityList({ page: 1 }, true)
    },
    
    // 清理状态
    clearState() {
      this.opportunityList = []
      this.currentOpportunity = null
      this.lastFetchTime = 0
    }
  }
}) 